'''
Created on 18/gen/2010

@author: syn
'''
from ui.GladeBase import GladeBase
from ui import *
import gtk
from soap import *
from utils import string_hook, logger

NO_ENTITY = -1

class ManagePrint(GladeBase):
    def __init__(self, query=None, top_component=None):
        logger.debug("UI: %s instance created" % self.__class__)
        GladeBase.__init__(self, 'manage_print_frame', top_component)
        self._init_gui_components()
        
        # Setting up print list
        self._load_to_gui()
            
    def _init_gui_components(self):
        """
        Intialize gui components as needed. This is useful in the contructor or 
        binded with particular actions (for instance, a "clear" button, or "new" button) 
        """
        self.apply_button.set_sensitive(False)
        self.print_list.clear()

    def _retrieve_components(self):
        """
        Retrieve all used gui components from builder. This method is called in the
        GladeBase constructor
        """
        self.get_from_builder('apply_button')
        self.get_from_builder('print_list')
        self.get_from_builder('print_treeview')
        
    def _load_to_gui(self):
        self._init_gui_components()
        
        # Setting up print list
        prints = client.get_prints(None)
        for pr in prints:
            confirm = 1 if pr.date else 0
            date = str(pr.date) if pr.date else ""
            row = [pr.id, pr.name, pr.quantity, confirm, date, not confirm]
            self.print_list.append(row)
    
    def _has_valid_data(self):
        """
        Formal control for data in the input form.
        @return: boolean. 'True' when data is valid
        """
        
        return True
            
    def _save_data(self):
        """
        Save changes to db. 
        @return: 'True' if data have been successfully saved 
        """
        if not self._has_valid_data():
            return False
        
        try:
            for row in self.print_list:
                if not row[5]:
                    break
                if row[3]:
                    client.confirm_print(row[0])
        except Exception as e:
            get_error_dialog(self.get_top_component(), e)
        
        self._load_to_gui()
        self.apply_button.set_sensitive(False)
        return True
    
    # Signals
    def on_new_button_clicked(self, object, data=None):
        pass
    
    def on_apply_button_clicked(self, object, data=None):
        self._save_data()
    
    def on_delete_button_clicked(self, object, data=None):
        (model, iter) = self.print_treeview.get_selection().get_selected()
        if not iter:
            return
        
        if not model.get_value(iter, 5):
            generic_data_error("Printing has already been processed. Can't delete", 
                               self.print_treeview)
            return
        
        try:
            client.delete_print(model.get_value(iter, 0))
        except Exception as e:
            get_error_dialog(self.get_top_component(), e)
        
        self._load_to_gui()

    def on_print_changed(self, *args, **kwargs):
        self.apply_button.set_sensitive(True)

    def on_confirm_toggled(self, toggle_bt, path, data=None):
        if toggle_bt.get_active():
            toggle_bt.set_active(False)
            self.print_list[path][3] = 0
        else:
            toggle_bt.set_active(True)
            self.print_list[path][3] = 1
            
        self.apply_button.set_sensitive(True)
        